package com.yangyouqi.controller;

import com.sun.xml.internal.bind.v2.runtime.reflect.Lister;
import com.yangyouqi.dataobject.ProductCategory;
import com.yangyouqi.dataobject.ProductInfo;
import com.yangyouqi.service.CategoryService;
import com.yangyouqi.service.ProductInfoService;
import com.yangyouqi.utils.ResultVOUtils;
import com.yangyouqi.vo.ProductInfoVO;
import com.yangyouqi.vo.ProductVO;
import com.yangyouqi.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 买家商品
 *
 * @author 杨友奇
 * @Time 2018/5/27
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 查询所有上架商品并且展示出来
     */
    @GetMapping("/list")
    public ResultVO list() {
        //1、先查询所有上架商品
        List<ProductInfo> productInfoList = productInfoService.findUpAll();
        //2、查询类目（一次性查询）
        List<Integer> categoryTypeList = new ArrayList<>();

        for (ProductInfo productInfo : productInfoList) {
            categoryTypeList.add(productInfo.getCategoryType());
        }
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);


        //3、数据拼装
        List<ProductVO> productVOList = new ArrayList<>();
        for (ProductCategory productCategory : productCategoryList) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryType(productCategory.getCategoryType());
            productVO.setCategoryName(productCategory.getCategoryName());


            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo: productInfoList){
                if (productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    //新特性->将一个类复制到另一个类上面
                    BeanUtils.copyProperties(productInfo,productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setCategoryFoods(productInfoVOList);
            productVOList.add(productVO);
        }
        return ResultVOUtils.success(productVOList);
    }
}
